# core/plugin_loader.py
import importlib
import inspect
from pathlib import Path
from typing import List, Dict, Any


def route(path: str = "", method: str = "GET"):
    """路由装饰器（默认路径为类名小写，方法名小写）"""
    def decorator(func):
        func._route = {"path": path, "method": method.upper()}
        return func
    return decorator

# 在 scan_plugins 函数中添加调试日志
def scan_plugins() -> List[Dict[str, Any]]:
    """扫描插件目录，返回层级化路由信息"""
    plugins = []
    plugins_dir = Path("plugins")

    for plugin_dir in plugins_dir.iterdir():
        if not plugin_dir.is_dir() or plugin_dir.name.startswith("_"):
            continue
        plugin_name = plugin_dir.name
        print(f"插件名称：{plugin_name}")
        app_dir = plugin_dir / "app"
        hasApp = True
        if not app_dir.exists():
            print(f"插件 {plugin_name} 缺少 app 目录，跳过")
            app_dir = plugin_dir / "controller"
            if not app_dir.exists():
                print(f"插件 {plugin_name} 缺少 controller 目录，跳过")
                continue
            hasApp = False
        # AllFiles = []
        if not hasApp:
            AllFiles = plugin_dir.glob("**/controller/**/*.py")
        else:
            AllFiles = app_dir.glob("**/controller/**/*.py")
        # 递归扫描 app 目录下的所有 controller 路径（仅 .py 文件）
        print(f"扫描目录：{app_dir}",AllFiles)
        for controller_path in AllFiles:
            print(controller_path,'cccccccccccc')
            if controller_path.name.startswith("_"):
                continue
            print(f"发现控制器文件：{controller_path}")

            rel_path = controller_path.relative_to(app_dir)
            parts = rel_path.parts  # 示例：('user', 'controller', 'order', 'CreateOrder.py')
            print(f"路径拆分：{parts}")

            # 定位 controller 目录位置（确保在 app/controller 下）
            try:
                controller_dir_index = parts.index("controller")
            except ValueError:
                # print(f"文件 {controller_path} 不在 controller 目录下，跳过")
                controller_dir_index = False
                # continue

            # 控制器路径（多层用/连接，如 order/CreateOrder）
            # controller_path_parts = parts[controller_dir_index+1:-1]  # 示例：('order',)
            if controller_dir_index:
                controller_path_parts = parts[:controller_dir_index] + parts[controller_dir_index+1:-1]
            else:
                controller_path_parts = ""

            controller_path = "/".join(controller_path_parts)  # 'order/CreateOrder'（含文件名）
            print(f"控制器路径：{controller_path}")

            # 提取类名（文件名去掉.py）
            class_name = parts[-1].replace(".py", "")  # 'CreateOrder'

            # 动态导入模块（修正：拼接目录 + 文件名）
            if not controller_dir_index:
                module_import_path = ".".join([
                                                  "plugins", plugin_name
                                              ] + ["controller"] + [class_name])
            else:
                module_import_path = ".".join([
                                                  "plugins", plugin_name, "app"
                                              ] + list(parts[:-1]) + [class_name])  # 关键：添加 class_name（即文件名）
            print(f"尝试导入模块：{module_import_path}")

            try:
                module = importlib.import_module(module_import_path)
                print(f"模块导入成功：{module.__name__}")
            except Exception as e:
                print(f"模块导入失败：{e}")
                continue
            # 收集方法路由
            methods = []
            for method_name, func in inspect.getmembers(module, inspect.isfunction):
                if not hasattr(func, "_route"):
                    continue
                if method_name.startswith("_"):
                    continue
                if method_name == "route":
                    continue
                # 构建完整路径（插件/模块/控制器路径/方法路径）
                full_path = f"/plugins/{plugin_name}/{controller_path}/{class_name}/{func._route['path'].lstrip('/')}"
                full_path = full_path.replace("//", "/")
                print(f"完整路径：{full_path}")
                print(f"注册路由：{func._route['method']} {full_path}（参数：{inspect.signature(func).parameters}）")

                methods.append({
                    "path": full_path,
                    "method": func._route["method"],
                    "handler": func
                })
                print(f"收集方法路由：{full_path} ({func._route['method']})")

            # 记录插件路由信息
            plugins.append({
                "plugin_name": plugin_name,
                "module_name": parts[0],  # 示例：user
                "controller_path": controller_path,
                "class_name": class_name,
                "methods": methods
            })
            print(f"插件 {plugin_name} 扫描完成，共收集 {len(methods)} 个路由")

    print(f"插件扫描结束，共发现 {len(plugins)} 个插件")
    return plugins